require 'will_paginate'

class PictureController < ApplicationController

helper :site

	def delete
		@picture = Picture.find(params[:id])
		if session[:user_id] == @picture.user_id or User.find(session[:user_id]).is_admin
			['small.jpg', 'medium.jpg', 'large.jpg'].each do |file|
				if File.exists?("#{RAILS_ROOT}/public/images/storage/#{params[:id]}/#{file}")
					File.delete("#{RAILS_ROOT}/public/images/storage/#{params[:id]}/#{file}")
				end
			end
			if File.exists?("#{RAILS_ROOT}/public/images/storage/#{params[:id]}")
				Dir.rmdir("#{RAILS_ROOT}/public/images/storage/#{params[:id]}")
			end
			@picture.destroy
			redirect_to :action => "index", :controller => "site"
		end
	end

	def upload
		if request.post? and params[:picture]
			@picture = Picture.new(params[:picture])
			@picture.user_id = session[:user_id]
			if @picture.save
				redirect_to :action => "index", :controller => "site"
			end
		end
	end
	
	def show
		@picture = Picture.find(params[:id])
		@author = User.find(@picture.user_id)
		#@comment = Comment.find_by_picture_id(@picture[:id])
		@comment = Comment.paginate :page => params[:page] ? params[:page] : 1, :conditions => "picture_id == #{@picture[:id]}", :per_page => 10
		if session[:user_id]
			@vote = Vote.find(:first, :conditions => {:picture_id => @picture.id, :user_id => session[:user_id]})
		end
	end

	def preview
	  @picture = Picture.find(params[:id])
	  render :partial => 'preview'
	end
end
